package com.yuyou.fn.controller;

import com.alibaba.fastjson.JSONObject;
import com.yuyou.fn.common.lang.Tuple2;
import com.yuyou.fn.common.util.JWTToken;
import com.yuyou.fn.platform.service.IAccessTokenService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalTime;
import java.util.Date;
import java.util.Properties;

@Controller
@RequestMapping("/cas")
public class CasController {

    @Resource(name = "applicationConfig")
    private Properties applicationConfig ;



    @RequestMapping("/login")
    public String login(  @RequestParam("returnUrl") String returnUrl , @RequestParam(value = "loginWay" , defaultValue = "sms") String loginWay ) throws UnsupportedEncodingException {

        JSONObject loginInfo = new JSONObject();
        loginInfo.put("returnUrl" ,returnUrl );
        loginInfo.put("loginWay" ,loginWay );
        String redirectUrl = applicationConfig.getProperty("cas.serverName") + "/cas/bridge/" + Base64.encodeBase64URLSafeString( loginInfo.toJSONString().getBytes("utf-8")) +"/bridge";
        return "redirect:" + applicationConfig.getProperty("cas.casServerUrlPrefix")+"login?service="+redirectUrl+"&getexecution=true" ;
    }

    @RequestMapping("/bridge/{loginInfo}/bridge")
    public String  bridge(@PathVariable("loginInfo") String loginInfo , HttpServletRequest request ) throws UnsupportedEncodingException {
        JSONObject loginInfoJSON = JSONObject.parseObject( new String( Base64.decodeBase64(loginInfo) ,"utf-8") );

        String[] urls = loginInfoJSON.getString("returnUrl").split("#");

        String ticket = JWTToken.generate("ticket" , Tuple2.asMap(Tuple2.of("ppId" ,request.getUserPrincipal().getName() )) , new Date(System.currentTimeMillis() + ( 60 * 1000 )),"2019");

        if(urls[0].contains("?")){
            urls[0] += "&ticket=" + ticket;
        }else{
            urls[0] += "?ticket=" + ticket;
        }

        //ppId暴露在前端可能存在安全隐患，更好的动态且有时效性的ticket
        return "redirect:" + StringUtils.join(urls , "#");
    }

}
